﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlServerCe;
using System.Data.Entity;
using System.Web.Hosting;
using System.IO;
using System.Data.Entity.Infrastructure;

namespace DYSales.Web
{
    public class conCE
    {
        internal static string constring = @"Data Source=|DataDirectory|\data.sdf; Password = 123456;";
        static SqlCeConnection conn;
        internal static SqlCeConnection GetConn()
        {
            Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", conCE.constring);
            string folder = HostingEnvironment.MapPath(@"~\App_Data");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            if (!File.Exists(HostingEnvironment.MapPath(@"~\App_Data\data.sdf")))
            {
                using (EntityContext ec = new EntityContext())
                {
                    ec.Database.Initialize(true);
                }
            }
            if (conn == null)
            {
                conn = new SqlCeConnection(constring);
                conn.Open();
            }
            return conn;
        }
        static SqlCeCommand cmdd;
        internal static void ExcuteSql(string sql)
        {
            if (cmdd == null)
            {
                cmdd = GetConn().CreateCommand();
            }
            cmdd.CommandText = sql;
            cmdd.ExecuteNonQuery();
        }

        internal static SqlCeDataReader ExcuteSqlReader(string sql)
        {
            if (cmdd == null)
            {
                cmdd = GetConn().CreateCommand();
            }
            cmdd.CommandText = sql;
            return cmdd.ExecuteReader();
        }

        internal static void Dispose()
        {
            try
            {
                conn.Close();
                conn.Dispose();
                conn = null;
            }
            catch { }
        }
    }
}